package com.tyson.server.controller;

import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;


import com.tyson.server.autogenerator.pojo.Admin;
import com.tyson.server.autogenerator.pojo.AdminLoginDto;
import com.tyson.server.autogenerator.service.IAdminService;
import com.tyson.server.common.Const;
import com.tyson.server.common.Result;
import com.tyson.server.service.IVerifyCodeGen;
import com.tyson.server.service.impl.SimpleCharVerifyCodeGenImpl;
import com.tyson.server.util.RedisUtil;
import com.tyson.server.util.VerifyCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;
import java.util.UUID;

@Api(tags = "LoginController")
@RestController
@Slf4j
public class LoginController {
    @Autowired
    private Producer producer;
    @Autowired
    RedisUtil redisUtil;

    @Autowired
    private IAdminService adminService;


    @ApiOperation(value = "登录之后返回token")
    @PostMapping("/login")
    public Result login(@RequestBody AdminLoginDto adminLoginDto, HttpServletRequest request) {
        return adminService.login(adminLoginDto.getUsername(), adminLoginDto.getPassword(), request);
    }


    @ApiOperation(value = "退出登录")
    @GetMapping("/loginout")
    public Result logout() {
        return Result.succ("注销成功！");
    }


    @ApiOperation(value = "获取当前登录用户信息")
    @GetMapping("/admin/info")
    public Admin getAdminInfo(Principal principal) {
        //principal是在登录成功后设置的Spring security的上下文对象 可以拿到username等信息
        if (null == principal) {
            return null;
        }
        String username = principal.getName();
        Admin admin = adminService.getAdminByUserName(username);
        admin.setPassword(null);
        return admin;
    }

    /**
     * 获取验证码
     */
    @GetMapping("/captchar")
    public void captchar(HttpServletRequest request, HttpServletResponse response) {
        IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();
        try {
//设置长宽
            VerifyCode verifyCode = iVerifyCodeGen.generate(80, 28);
            String code = verifyCode.getCode();
//将VerifyCode绑定session
            request.getSession().setAttribute("VerifyCode", code);
//设置响应头
            response.setHeader("Pragma", "no-cache");
//设置响应头
            response.setHeader("Cache-Control", "no-cache");
//在代理服务器端防止缓冲
            response.setDateHeader("Expires", 0);
//设置响应内容类型
            response.setContentType("image/jpeg");
            response.getOutputStream().write(verifyCode.getImgBytes());
            response.getOutputStream().flush();
        } catch (IOException e) {
        }
    }

    /**
     * 图片验证码
     */
    @GetMapping("/captcha")
    public Result captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String code = producer.createText();
        String key = UUID.randomUUID().toString();
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Img = str + encoder.encode(outputStream.toByteArray());

        // 存储到redis中
        redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);
        log.info("验证码 -- {} - {}", key, code);

        return Result.succ(
                MapUtil.builder()
                        .put("token", key)
                        .put("base64Img", base64Img)
                        .build()
        );
    }
}
